FastAPI + JWT Authentication: Implementing Simple User Login Verification

This article introduces the complete process of implementing user login authentication using FastAPI and JWT, with the core steps as follows: 1. **Environment Preparation**: Install FastAPI, uvicorn, python-jose (for JWT handling), passlib[bcrypt] (for password hashing), and python-multipart (for form processing). 2. **Core Concepts**: JWT enables stateless authentication, FastAPI dependencies reuse verification logic, and passwords are stored using bcrypt hashing. 3. **Code Implementation**: - Configure JWT parameters (secret key, algorithm, expiration time) and simulate a user database. - Use passlib to generate password hashes and define utility functions for JWT generation and verification. - Define OAuth2 dependencies to extract tokens, create a login endpoint (/token) to validate users and return tokens, and protected endpoints (/users/me) to return user information after token validation. 4. **Running Tests**: Start the uvicorn service, use Swagger UI to test the login endpoint for obtaining a token, and then use the token to access protected endpoints. 5. **Key Knowledge Points**: Dependency reuse for verification logic, secure handling of JWT secrets (environment variables for production), and password hashing to prevent plaintext leaks. Through the above steps, the implementation

Read More
FastAPI + Uvicorn: Basic Configuration for Local Development and Deployment

This article introduces the web development and deployment process using FastAPI with Uvicorn. FastAPI is a high-performance Python framework supporting asynchronous operations and automatic API documentation. Uvicorn, as an ASGI server, is the recommended deployment tool for FastAPI, and their combination enables efficient development. **Environment Installation**: First, create a virtual environment (e.g., `python -m venv venv`), activate it, and then install dependencies with `pip install fastapi uvicorn`. **Development Configuration**: Write `main.py`, define routes (e.g., root route `/` and parameterized route `/items/{item_id}`), and start the server with `uvicorn main:app --reload` for auto-reloading in development mode. Verify the interface by accessing `http://127.0.0.1:8000`. **Production Deployment**: Use the basic command `uvicorn main:app --host 0.0.0.0 --port 8000`. Specify the number of worker processes with `--workers` for multi-processing. Ensure the deployment server opens the port and manage processes via `nohup` or `systemd`. **Common Issues**: For port conflicts, change the port. If the service is unreachable, confirm `--host 0.0.0.0` and firewall settings. If installation fails, update pip or check Python version compatibility.

Read More
FastAPI Practical: Building RESTful APIs with GET and POST Methods

FastAPI is a Python-based modern web framework with advantages such as high performance (close to Node.js and Go), automatic API documentation generation (Swagger UI and ReDoc), type hint support, and ease of use. For environment preparation, install FastAPI and uvicorn (recommended ASGI server). Quick start example: Create a root path endpoint (`@app.get("/")`) that returns a welcome message. Run with the command `uvicorn main:app --reload`. GET method practice includes: ① Path parameters (e.g., `/users/{user_id}`) with automatic type validation; ② Query parameters (e.g., `/users/filter?name=张三`) for filtering. POST method requires defining a Pydantic model (e.g., `UserCreate`) to receive JSON data, with automatic format validation and new user creation. FastAPI automatically generates API documentation; access `http://localhost:8000/docs` (Swagger UI) or `/redoc` to test interfaces. Its core advantages are summarized as: type hints, data validation, and interactive documentation, making it suitable for quickly building reliable RESTful APIs.

Read More
Beginners Guide: How to Use Pydantic for Data Validation in FastAPI

This article introduces the core content of using Pydantic for data validation in FastAPI. Data validation is crucial in web development, and FastAPI leverages the built-in Pydantic library to achieve efficient validation. Pydantic enables automatic checking of input validity by defining data models based on type hints (inheriting from BaseModel), supporting both basic and complex types (e.g., list, dict), and distinguishing between required fields (without default values) and optional fields (with default values). In FastAPI, Pydantic models are mainly used to handle request data (such as POST request bodies). FastAPI automatically parses and validates the data, returning a 422 error with detailed information if validation fails. Response data can also be validated using a Pydantic model via the response_model parameter to ensure the correct return format. Additionally, Pydantic supports custom validation, such as setting field constraints (e.g., length, range) through Field or using custom functions (e.g., email format verification). The advantages of Pydantic lie in automatic validation, user-friendly error messages, type safety, and flexible extension. It prevents program crashes or security vulnerabilities caused by invalid data, making it a core tool for building secure and robust APIs with FastAPI.

Read More
Flask from Beginner to Master: Core Technologies and Extended Applications

Flask is a lightweight Python Web framework centered on a "micro" design. It is flexible and supports rich extensions, making it suitable for both beginners and large-scale projects. Installation is recommended with a virtual environment followed by `pip install flask`. Core technologies include routing (dynamic parameters, multiple HTTP methods), the Jinja2 template engine (variables, conditional rendering), and static file management. Advanced core functionalities involve session management, redirection, database operations with Flask-SQLAlchemy, and user authentication with Flask-Login. Commonly used extensions include Flask-WTF (forms), Flask-RESTful (APIs), and Flask-Admin (backend management). For production deployment, options include Gunicorn/Nginx, cloud platforms (PythonAnywhere, Heroku), or Docker. Through practice and extended components, Flask enables full-stack development from small projects to complex applications.

Read More
Flask and Database: SQLAlchemy Model Definition

This article introduces the method of database interaction in Flask using SQLAlchemy (an ORM tool). The core steps are as follows: First, install Flask and Flask-SQLAlchemy. For development environment with SQLite, no additional driver is needed; other databases require corresponding drivers (e.g., pymysql for MySQL). Next, initialize the Flask application and SQLAlchemy, configure the SQLite database connection (URI: sqlite:///mydatabase.db), and disable modification tracking to reduce overhead. Then, define models: Use Python classes inheriting from db.Model to map database tables. Class attributes correspond to fields (e.g., id as primary key, username as non-null unique string), supporting various field types (Integer, String, Text, etc.). Table relationships are defined using foreign keys and relationships (e.g., one-to-many relationship between User and Article). Create tables by executing db.create_all() within the application context, which automatically generates the table structure. Finally, perform CRUD operations via db.session: Add using add + commit, query using query.all/filter_by, update by directly modifying attributes then commit, and delete using delete + commit. Summary: Model definition is the foundation of Flask database interaction. Data operations can be implemented by mapping fields and relationships through class attributes, with table relationships extensible for future use.

Read More
Practical Flask Project: A Tutorial for Developing a Personal Blog System

This tutorial introduces the complete process of building a personal blog with Flask. First, install Flask and its extensions (SQLAlchemy for ORM, Login for user authentication, WTF for form handling, and Bootstrap for page styling). Create the project directory structure and define User (with password encryption) and Post (associated with users) data models in models.py. Initialize the Flask application in app.py, configure the SQLite database, and implement core routes such as the homepage article list, single article details, publishing articles by logged-in users, and login/logout functionality. Use Bootstrap templates (with base.html as the base, inheriting to extend the homepage, detail page, and article-writing page). After running, the blog is accessible and supports article publishing. Future enhancements can include registration, editing, and commenting. This project helps you master basic Flask applications, database operations, and user authentication.

Read More
Handling Flask Forms: WTForms Fields and Form Submission

This article introduces the core knowledge points of handling forms in Flask using `Flask-WTF` (based on WTForms). First, forms rely on the `Flask-WTF` extension, which needs to be installed via `pip install flask-wtf`. WTForms provides various field types (such as `StringField`, `PasswordField`, `SubmitField`, etc.) corresponding to HTML input controls. To define a form class, you need to inherit from `FlaskForm`, declare fields in the class, and set validators (e.g., `DataRequired`, `Length`, `Email`). In the example, the `LoginForm` includes username, email, password, and a submit button, with clear validation rules for each field. In view functions, you need to create a form instance, use `form.validate_on_submit()` to check POST requests and data validation. If validation passes, process the data (e.g., login verification); otherwise, render the template. The template should use `form.hidden_tag()` to generate CSRF tokens for security and display error messages using `form.errors`. The core principles include form definition, request handling, data validation, template rendering, and CSRF protection. Common issues such as missing CSRF tokens require checking `form.hidden_tag()` and `SECRET_KEY`. Validation failures can be troubleshooted via `form.errors`, and password inputs should use [note: the original text ends abruptly here, so the translation follows the provided content].

Read More
Flask Route Parameters: Dynamic URLs and Variable Capture

Flask dynamic URL parameters are used to handle requests for variable resources. They capture the variable parts of the URL using the `<parameter_name>` syntax and pass them to view functions. By default, parameters are of string type, but they support various built-in type restrictions: `int` (only integers, non-integers return 404), `float` (floating-point numbers), `path` (path parameters allowing slashes), etc. For multi-parameter routes, multiple parameters need to be received correspondingly, such as `/book/<string:book_name>/<int:chapter>`. Typical application scenarios include user centers (`/user/<username>`) and article details (`/post/<int:post_id>`). It should be noted that parameter names must be consistent, the order of route matching matters, and parameters cannot be omitted. Dynamic routing enables flexible handling of personalized content and enhances the scalability of web applications.

Read More
Getting Started with Flask Templates: Jinja2 Variables and Control Structures

This article introduces the basic usage of the Jinja2 engine in the Flask template system, which helps dynamically display data on web pages. The core content includes: 1. **Jinja2 Variables**: Data is passed from the backend view function via `render_template`, and variables in the template are rendered using `{{ variable_name }}`. It supports various types such as strings, numbers, lists, and dictionaries. An example demonstrates variable rendering through user information (name, age, hobby list). 2. **Control Structures**: Conditional judgments use `{% if ... %}` (e.g., checking if age is adult), and loops use `{% for ... %}` (iterating over a list). The `loop` variable (e.g., `loop.first`, `loop.last`) is utilized to optimize iteration logic. 3. **Filters**: Variables are processed using the `|` syntax, such as `upper` for uppercase conversion, `round` for rounding, and `safe` for rendering HTML (with security precautions noted). The article summarizes the core methods to achieve page dynamicity through variables, control structures, and filters, laying the foundation for advanced template features like inheritance and macros.

Read More
Flask Session Management: Implementation of User Login State Persistence

This article introduces Flask's session management, where the core is maintaining user state through the `session` object, implemented based on Cookies. The usage involves two steps: importing `session` and setting a secret key (SECRET_KEY, requiring a random string in production), and setting the session expiration period (default is invalid after browser closure, extendable via `permanent_session_lifetime`). Taking "Login-Verification-Logout" as an example, the process is as follows: the frontend form inputs account credentials, the backend validates them, then sets `session["username"]` with `permanent=True` to achieve persistent login. The `login_required` decorator checks the session to ensure only logged-in users access sensitive pages. During logout, `session.pop` is used to clear the state. For security, the secret key must be kept confidential (avoid hardcoding), and the session should only store necessary information (e.g., user ID) without sensitive data. Through these steps, persistent management of user login status can be achieved, enhancing website user experience.

Read More
From 0 to 1: Flask Project Development Process and Best Practices

This article introduces Flask, a lightweight Python web framework. First, its features are defined: concise and flexible, like a "toolbox," suitable for beginners and small-to-medium-sized projects. For the development environment, Python (3.7+) and Flask need to be installed, and a virtual environment should be created to avoid dependency conflicts. The project development process includes: creating a virtual environment, establishing a basic structure with app.py (entry point), static (static files), and templates (templates). The first "Hello World" example demonstrates route definition and starting the development server. Advanced content covers dynamic routing, Jinja2 template rendering, form handling (including flash message feedback), and Flask-SQLAlchemy database operations. Best practices emphasize configuration management (environment variables or config.py), blueprint for module splitting, error handling (404/500 pages), logging, and testing. Deployment recommends using gunicorn locally and cloud platforms like PythonAnywhere and Heroku. In summary, core concepts such as routes, templates, forms, databases, and project structure need to be mastered. Complexity can be enhanced through extensions (Celery, RESTful), and practice is key.

Read More
Flask: Core Concepts and Basic Applications

Flask is a lightweight Python Web framework with a "micro" design philosophy, featuring a streamlined core functionality that enables complex requirements through extensible components. Key reasons for choosing it include: being lightweight and flexible (allowing component selection based on needs), having low learning curve, strong extensibility (e.g., via third-party extensions like ORM and user authentication), and offering user-friendly documentation. Core concepts encompass routing (mapping URLs to functions with support for dynamic parameters), view functions (handling requests and returning responses), request/response handling (using `request` to fetch data and `response` to deliver content), templates (rendered by Jinja2 for dynamic pages), static files (CSS/JS, etc.), and extension utilities. A basic application example involves writing `app.py` to define routes, render templates, and run the service. It is suitable for starting with small projects and gradually expanding, with recommendations for learning through official documentation and other resources.

Read More
Flask User Authentication: Implementing Login Functionality with Flask-Login

This article introduces the method to implement user login functionality in web applications using Flask-Login. As a lightweight extension, Flask-Login simplifies user session management, login/logout operations, and permission control. The core steps include: installing `flask` and `flask-login`; initializing the application and configuring `LoginManager` with a redirect route for unauthenticated access; creating a user model that inherits from `UserMixin` to define user ID, password, and other information; loading the user from the session via the `user_loader` callback function; implementing login view to validate credentials and using `login_user` to record the session, while `logout_user` is used for logout; and protecting routes requiring authentication with the `@login_required` decorator. A mock user database and template rendering are used to support the basic login flow. Notices emphasize secure password storage (hashing), secure session key configuration, and suggest extending with features like "remember me" and permission management. Flask-Login enables quick implementation of core authentication functionality through a concise API, making it suitable for rapid entry into web user authentication development.

Read More
Flask View Functions: From Returning HTML to Dynamic Data

This article introduces the core role and usage of view functions in Flask. View functions are the core component that handles user requests and returns responses, acting as a bridge connecting user access and content generation. Firstly, view functions can return simple strings, and Flask will automatically convert them into HTML responses (such as the "Hello, Flask!" example). Secondly, `render_template` is used to load HTML templates from the `templates` folder, enabling static page rendering. Dynamic data processing is a key focus: by leveraging the Jinja2 templating engine, view functions can pass variables (e.g., current time) to templates for rendering using `{{ variable }}`. They also support loops (`{% for %}`) and conditional judgments (`{% if %}`) to display dynamic lists. Route parameters (e.g., `/profile/<user_id>`) can be used to obtain dynamic parameters from URLs, or the `request` object can handle request parameters (e.g., URL parameters, form data). In the comprehensive example, a dynamic blog list combines parameter processing with template rendering to implement article filtering by author. View functions support static content, dynamic data (variables, loops, conditions), and parameter handling, making them the foundation for building interactive web applications.

Read More
Flask and Frontend Interaction: AJAX Requests and JSON Responses

This article introduces the method of implementing front-end and back-end data interaction in Flask using AJAX and JSON. In a front-end and back-end separated architecture, the front-end is responsible for interface interaction, while the back-end handles business logic. AJAX enables asynchronous requests, and JSON serves as the data exchange format. The core process is: front-end initiates an asynchronous request → back-end processes and returns JSON → front-end parses and renders the data. Practical example: Create `app.py` in Flask, where the `/` route renders the front-end page, and the `/api/get_data` route returns simulated JSON data (including status, message, and a list). The front-end uses `fetch` to asynchronously request `/api/get_data`, and updates the page after obtaining the data. Key knowledge points include: using `jsonify` on the back-end to return JSON, using `async/await` on the front-end to simplify asynchronous code, supporting GET/POST requests and data transfer (e.g., `request.get_json()` to receive front-end data). The core steps are clear, and it can be extended to scenarios such as form submission and database interaction.

Read More
Flask Project Structure: From Small Projects to Large Applications

The article emphasizes the importance of Flask project structure planning, which can avoid code chaos and enhance development and maintenance efficiency. It evolves from simple to complex in stages: a single file is only suitable for quick verification but becomes hard to maintain due to code clutter; medium-sized projects split into templates, static files, but further structural standardization is needed, such as separating configurations (config.py), centralizing route management (routes.py), and isolating data models (models.py); large projects use Blueprints to split functional modules (e.g., main module, user module, blog module), achieving single responsibility and independent reusability. Best practices include: managing dependencies with requirements.txt, storing sensitive configurations in environment variables, enabling debug mode during development and disabling it in production, and adding a test directory. The core principle is "splitting functions and ensuring single responsibility," and developing the habit of standardized structures facilitates future expansion.

Read More
Blueprint in Flask: A Practical Approach to Modular Application Development

Flask blueprints are used to address the problem of chaotic route management as the application grows in functionality. They enable grouping routes by different modules, resulting in a clear project structure and easier code maintenance. The core advantages of using blueprints include modular grouping (such as splitting user and product functionalities), code isolation for team collaboration, reduced circular import errors, and support for reuse. In practice, first design the project structure: the main app.py imports blueprints from two modules (user and product), and each module has a routes.py to define routes. For example, user/routes.py creates the user blueprint and defines routes like /profile and /login, with product/routes.py following a similar pattern. The main app.py registers these blueprints using register_blueprint, and a url_prefix can be added for unified prefixes (e.g., /user/profile). Advanced usage includes isolating templates (template_folder) and static files (static_folder), as well as controlling path prefixes and subdomains through url_prefix and subdomain. Blueprints modularize complex applications and reduce maintenance costs. It is recommended to use them from the early stages of a project to foster good development habits.

Read More
Flask Database Operations: A Beginner's Guide to SQLAlchemy ORM

ORM solves the maintenance difficulties of directly writing SQL in web development by simplifying operations through mapping database table structures with Python objects. Flask + SQLAlchemy is a commonly used combination, and you need to install `flask` and `flask-sqlalchemy` first. During initialization, configure the SQLite database path (e.g., `sqlite:///mydatabase.db`) and disable modification tracking. Define model classes (such as User) that inherit from `db.Model`, with class attributes corresponding to table fields (including primary keys and constraints). Use `db.create_all()` to automatically generate the tables. Core operations are session-based (`db.session`): creation (`add` + `commit`), reading (`query.all()`/`filter_by()`/`get()`), updating (modify attributes + `commit`), and deletion (`delete` + `commit`). After mastering this process, you can extend to databases like MySQL and explore advanced features such as relationship models.

Read More
Python Web Development: A Quick Start with the Lightweight Flask Framework

This article introduces the basic content of Flask, a lightweight Python web framework, including: **Definition and Features**: Flask is a lightweight and flexible Python framework that encapsulates repetitive tasks (such as HTTP handling and route management). It has a low learning curve, strong scalability, and is suitable for quickly developing small websites or APIs. **Environment Setup**: Install it via `pip install flask` and verify the version with `flask --version`. **First Application**: Create `app.py` to instantiate Flask, define the root route with `@app.route('/')`, and start the server with `app.run(debug=True)`. Accessing `http://127.0.0.1:5000` will display "Hello, Flask!". **Routes and View Functions**: Support basic routes (e.g., `/about`) and dynamic parameters (e.g., `/user/<username>`). Parameter types include integers, paths, etc. (e.g., `/post/<int:post_id>`). **Templates and Static Files**: Use the Jinja2 template engine for dynamic rendering of variables, loops, and conditions (in the `templates` folder); static resources (CSS/JS) are placed in the `static` folder, accessed via `url_for('static', filename='...')`.

Read More
Frontend and Backend Collaboration: Flask Template Rendering HTML Dynamic Data Example

This article introduces the basic method of implementing front - end and back - end data linkage rendering using the Flask framework. First, you need to install Flask and create a project structure (including app.py and templates folder). The back - end defines routes through @app.route, the view function prepares data (such as a user information dictionary), and passes the data to the front - end template using render_template. The front - end template uses Jinja2 syntax (variable output {{ }}, conditional judgment {% if %}, loop rendering {% for %}) to display the data. After running app.py and accessing localhost:5000, you can see the dynamically rendered user information. The core steps are: back - end data preparation and route rendering, and front - end template syntax parsing. After mastering this process, you can expand more data transfer and template reuse (such as multi - conditional judgment, list rendering), which is the basis for front - end and back - end collaboration in web development.

Read More
Beginners' Guide: Variables and Loop Syntax in Django Template Engine Jinja2

This article introduces the core syntax of variables and loops in the Django template engine Jinja2. The template engine combines backend data with HTML templates to generate web pages. As Django's default engine, Jinja2 is the focus here, with emphasis on variables and loops. Variable syntax: Variables are enclosed in double curly braces {{}}. They support strings, numbers, booleans, and lists (displayed directly). Dictionaries can be accessed using dot notation (.) or square brackets ([]), such as {{ user.name }} or {{ user["address"]["city"] }}. Note that undefined variables will cause errors, and variables in templates are not modifiable. Loop syntax: Use {% for variable in list %} to iterate. It is accompanied by forloop.counter (for counting), first/last (for marking the first and last elements), and {% empty %} to handle empty lists. Examples include looping through lists or lists of dictionaries (e.g., each dictionary in a user list). Summary: Mastering variables and loops enables quick data rendering. Subsequent articles will cover advanced topics such as conditions and filters.

Read More
3 Minutes to Understand: Defining and Using Routes in Python Web Development

This article introduces the concept of "routing" in web development and its application under the Flask framework. Routing is analogous to a restaurant waiter, responsible for receiving user requests (such as accessing a URL) and matching the corresponding processing logic (such as returning a web page), serving as the core that connects user requests with backend logic. The article focuses on the key usages of routing in Flask: 1. **Basic Routing**: Defined using `@app.route('/path')`, corresponding to a view function returning a response, such as the homepage at the root path `/`. 2. **Dynamic Parameters**: Receive user input via `<parameter_name>` or `<type:parameter_name>` (e.g., `int:post_id`), with automatic type conversion. 3. **HTTP Methods**: Specify allowed request methods using `methods=['GET','POST']`, combined with the `request` object to determine the request type. 4. **Reverse Lookup**: Dynamically generate routing URLs using `url_for('function_name', parameters)` to avoid hardcoding. The core is to achieve request distribution, parameter processing, and page interaction through routing. Mastering these basics can support page jumps and data interaction in web applications.

Read More
Django ORM Practical Guide: CRUD Operations with SQLite Database

This article introduces the operation methods of Django framework combined with SQLite database, focusing on the use of ORM tools. Django ORM allows database operations through Python code, avoiding the need to write complex SQL statements. SQLite is lightweight and easy to use, making it suitable for development and learning. Preparatory work includes: creating a new Django project (`startproject`/`startapp`), configuring SQLite by default in `settings.py`, defining models (such as a `User` class), and executing `makemigrations` and `migrate` to generate database tables. The core is the CRUD operations of Django ORM: **Creation** can be done via `create()` or instantiation followed by `save()`; **Reading** uses `all()`, `filter()`, `get()` (supporting conditions and sorting); **Updating** uses `update()` for batch operations or querying first then modifying; **Deletion** uses `delete()` for batch operations or querying first then deleting. It is important to note the lazy execution of QuerySet, using `unique=True` to prevent duplicates, and exception handling for `get()`. Summary: By defining models, migrating table structures, and calling ORM methods, database operations can be completed. The code is concise and easy to maintain, making it suitable for quickly getting started with web development.

Read More
RESTful API Getting Started: Developing a Simple GET Data Interface with Flask

This article introduces the concept of RESTful APIs and implementing a GET interface with Flask. RESTful APIs are HTTP-based front-end and back-end interaction architectures centered on resources, manipulating resources through GET/POST/PUT/DELETE operations, stateless, and returning JSON data. Flask is chosen for its lightweight and flexibility, making it suitable for beginner development. Flask can be installed via `pip install flask` (virtual environment is optional). Implementation involves two steps: first, define the root path `/` to return "Hello, Flask!", with the core code being the `@app.route('/')` decorator and the `return` statement with a string; second, implement the `/users` interface to return user list JSON data, requiring the import of `jsonify` and returning the converted list. After starting the application, access `http://localhost:5000/users` through a browser, curl, or Postman for testing. Core steps include: importing Flask, initializing the application, defining route functions, returning data, and starting the service. Future extensions can include more routes or database integration.

Read More
HTTP Requests and Responses: Fundamental Core Concepts in Python Web Development

In Python web development, HTTP is the core for communication between the client (e.g., a browser) and the server, based on the "request-response" mechanism. The client generates an HTTP request, which includes methods (GET/POST, etc.), URLs, header information (e.g., User-Agent, Cookie), and a request body (POST data). After processing, the server returns an HTTP response, which contains a status code (e.g., 200 for success, 404 for not found), response headers (e.g., Content-Type), and a response body (web pages/data). The process is: client sends a request → server parses and processes it → returns a response → client renders the response (e.g., HTML to render a web page). Python frameworks (e.g., Flask) simplify this process. In the example, Flask uses `request` to access the request and `return` to directly send back the response content. Understanding this mechanism is fundamental to web development and lays the foundation for advanced studies such as HTTPS and Cookies.

Read More